package com.hn.gege.im.config.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ws.schild.jave.*;

import java.io.File;

@Component
public class AudioUtil {

    //图片存储路径
    private static String FILE_PHYSICAL_PATH;

    @Value(value="${file.physical.path:D:/}")
    public void setFILE_PHYSICAL_PATH(String FILE_PHYSICAL_PATH) {
        this.FILE_PHYSICAL_PATH = FILE_PHYSICAL_PATH;
    }


    /**
     * amr文件转换为mp3文件,返回MP3文件相对路径
     * @param filePath 文件相对路径 ,例如:file/11.amr
     */
    public static String changeTemp(String filePath) throws EncoderException {

        File amrFile = new File(FILE_PHYSICAL_PATH , filePath);   //源文件

        int index = filePath.lastIndexOf(".");
        String fileName = filePath.substring(0, index);
        //mp3文件的相对路径
        String mp3FilePath = fileName + ".mp3";
        File mp3File = new File(FILE_PHYSICAL_PATH, mp3FilePath);   //生成目标文件


        //设置参数
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        Encoder encoder = new Encoder();

        //文件转换
        MultimediaObject multimediaObject = new MultimediaObject(amrFile);
        encoder.encode(multimediaObject, mp3File, attrs);
        return mp3FilePath;
    }

}
